<template>
  <div>
    <el-form 
      ref="form" 
      :model="form"
      label-width="120px"
      label-position="left"
      :rules="rules"
      class="el-form"
    >
      <el-container>
        <el-aside width="150px">
          <el-image
            style="width: 150px; height: 150px"
            :src="form.photo"
            :fit="fit"
          ></el-image>
          <div class="aside-text">JPG, JPEG, PNG格式, 文件大小不能超过2M</div>
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="$baseUrl + 'user/uploadImg'"
            :show-file-list="false"
            name="photo"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            :on-success="successHandle"
            :file-list="fileList"
          >
            <!-- https://imgtu.com/ -->
            <!-- https://api.uomg.com/api/image.baidu -->
            <el-button size="mini" class="aside-btn add-btn" native-type="file">上传图片</el-button>
          </el-upload>
          <!-- <input type="file" ref="upload" accept="image/png, image/jpeg" @click="submitImg"> -->
        </el-aside>
        <el-main>
          <div class="main">
            <el-form-item label="账号" prop="username">
              <el-input v-model="form.username" :disabled="id" style="width: 300px" placeholder="成员唯一标识，不可更改(字母+数字)"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" style="width: 300px" placeholder="性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" style="width: 300px" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" style="width: 300px" placeholder="请输入昵称"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" style="width: 300px" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="form.confirmPassword" type="password" style="width: 300px" placeholder="请再次输入相同的密码"></el-input>
            </el-form-item>
          </div>
        </el-main>
      </el-container>
      <el-divider></el-divider>
      <div class="main">
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="form.tel" style="width: 350px" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" style="width: 350px" placeholder="可通过邮箱验证身份"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="birthday"
            placeholder="请选择出生日期"
            style="width: 350px"
          ></el-date-picker>
        </el-form-item>
      </div>
      <el-divider></el-divider>
      <div class="posi-inform">任职信息</div>
      <div class="main">
        <el-form-item label="职位" prop="roles">
          <el-select
            v-model="form.roles"
            multiple
            style="width: 350px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="dept">
          <el-select v-model="form.dept" style="width: 350px" placeholder="请选择">
            <el-option v-for="item in deptList" :key="item.id" :label="item.deptName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工状态" prop="status">
          <el-select v-model="form.status" style="width: 350px" placeholder="请选择">
            <el-option label="初始" :value="1"></el-option>
            <el-option label="在职(试用期)" :value="2"></el-option>
            <el-option label="在职(已转正)" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" prop="hiredate">
          <el-date-picker
            v-model="form.hiredate"
            type="date"
            placeholder="请选择入职日期"
            :disabled="id"
            style="width: 350px"
          ></el-date-picker>
        </el-form-item>
      </div>
      <el-divider></el-divider>
    </el-form>
    <div class="foot">
      <button class="foot-btn btn-color" @click="dataSubmit">保存</button>
    </div>
  </div>
</template>

<script>
// import { beforeunloadHandler } from '../../utils/utils'
import defaultAvatar from '../../assets/img/default-avatar'
export default {
  props: ['evaItem'],
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      id: '',
      form: {
        username: '',
        password: '',
        confirmPassword: '',
        nickname: '',
        name: '',
        sex: '',
        tel: '',
        email: '',
        roles: [],
        birthday: '',
        hiredate: '',
        status: '',
        dept: '',
        photo: defaultAvatar
      },
      roleList: [],
      deptList: [],
      fileList: [],
      rules: {
        username: { required: true, message: '请选择账号', trigger: 'blur'},
        password: { required: true, message: '请输入密码', trigger: 'blur'},
        confirmPassword: { required: true, validator: validatePass, trigger: 'blur'},
        status: { required: true, message: '请选择员工状态', trigger: 'blur'},
        dept: { required: true, message: '请选择部门', trigger: 'blur'},
        email: { required: true, pattern: '^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', message: '邮箱格式错误', trigger: 'blur'},
        tel: { required: true, pattern: '^1[0-9]{10}$', message: '手机格式错误', trigger: 'blur'},
      }
    }
  },
  created() {
    this.getDeptList()
    this.getRoleList()
    // this.id = this.$route.params.id != "undefined" ? this.$route.params.id : ''
    this.id = this.$route.params.id
    this.init(this.id)
  },
  methods: {
    init(id) {
      if (id) {
        this.$http('user/selectUserById1', 'post', {id}, false, resp => {
          console.log(resp.list);
          if (resp.code == 200) {
            resp.list.roles = JSON.parse(resp.list.roles)
            this.form = resp.list
            this.form.dept = this.form.dept - "0"
            this.form.roles = this.form.roles
            this.form.confirmPassword = this.form.password
            // if (this.form.status == 1) {
            //   this.form.status = '初始'
            // } else if (this.form.status == 2) {
            //   this.form.status = '在职(试用期)'
            // } else if (this.form.status == 3) {
            //   this.form.status = '在职(已转正)'
            // } else if (this.form.status == 4) {
            //   this.form.status = '离职'
            // }
          }
        })
      }
    },
    dataSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!this.id) {
            console.log(this.form);
            this.$http('user/insert', 'post', this.form, false, resp => {
              if (resp.code == 200) {
                this.$message({
                  message: '添加成功',
                  type: 'success',
                  duration: 1200
                })
                setTimeout(() => {
                  this.$router.push({name: 'User', params: {tabClose: true}})
                }, 1200);
                
              } else {
                this.$message({
                  message: '添加失败',
                  type: 'error',
                  duration: 1200
                })
              }
            })
          } else {
            this.form.id = this.id
            console.log(this.form);
            this.$http('user/update', 'post', this.form, false, resp => {
              if (resp.code == 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 1200
                })
                setTimeout(() => {
                  this.$router.push({name: 'User', params: {tabClose: true}})
                }, 1200);
                
              } else {
                this.$message({
                  message: '修改失败',
                  type: 'error',
                  duration: 1200
                })
              }
            })
          }
          // this.form = {}
        } else {
          return false
        }
      })
    },
    // 取消
    cancelHandle() {
      this.form = {}
      this.visible = false
    },
    // 获取部门
    getDeptList() {
      this.$http('dept/searchAllDept', 'get', null, true, resp => {
        if (resp.code == 200) {
          this.deptList = resp.list
          // console.log(this.deptList);
        }
      })
    },
    // 获取角色
    getRoleList() {
      this.$http('role/searchAllRole', 'get', null, true, resp => {
        if (resp.code == 200) {
          this.roleList = resp.list
        }
      })
    },
    successHandle(file) {
      console.log(file);
      this.form.photo = "http://" + file.data
    },
    // 上传文件之前的钩子
    handleBeforeUpload(file){
      if(!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
        })
      }
      let size = file.size / 1024 / 1024 / 2
      if(size > 2) {
        this.$notify.warning({
          title: '警告',
          message: '图片大小必须小于2M'
        })
      }
    },
  },
  // mounted() {
  //   window.addEventListener('beforeunload', e => beforeunloadHandler(e))
  // }
}
</script>

<style lang="scss" scoped>
@import './userAddOrUpdate.scss';
</style>